# _*_ coding: utf-8 _*_
# @Time:2024/5/16 14:51
# @Author:10917
# @File:serializers.py
from rest_framework.response import Response
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer


class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    """
    自定义令牌(token),加入自定义的字段返回
    """

    @classmethod
    def get_token(cls, user):
        token = super(TokenObtainPairSerializer, cls).get_token(user)

        # 添加额外信息  给access令牌解析时用的
        token['username'] = user.username
        token['email'] = user.email
        return token

    def validate(self, attrs):
        """
        定义登录成功后返回的数据格式字段  login，接口返回给前端用的
        :param attrs:
        :return:
        """

        try:
            data = super().validate(attrs)
            del data['access']
            del data['refresh']
            refresh = self.get_token(self.user)
            data['status'] = 1
            data['msg'] = '登录成功'

            info = {
                'refresh': str(refresh),
                'token': str(refresh.access_token),
                'username': self.user.username,
                'user_id': self.user.id
            }
            data['data'] = info

            return data
        except Exception:
            return {
                'status': 0,
                'msg': '账号/密码不正确,请检查重试',
                'data': []
            }
